package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.controller.other.BaseController;
import com.example.domain.Category;
import com.example.domain.Dish;
import com.example.domain.Employee;
import com.example.domain.other.DishFlavor;
import com.example.dto.DishCategoryDto;
import com.example.dto.DishCopiesDto;
import com.example.dto.DishDto;
import com.example.result.JsonResult;
import com.example.service.CategoryService;
import com.example.service.DishFlavorSerivce;
import com.example.service.DishService;
import com.example.untils.RedisContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *   菜品
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController extends BaseController {    //菜品表
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorSerivce dishFlavorSerivce;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //新增菜品
    @PostMapping("/save")
    public JsonResult save(@RequestBody DishDto dishDto){
        log.info("图片:"+dishDto.getImage());

        Dish dish = dishDto.gainDish();
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName,dish.getName());
        Dish result = dishService.getOne(queryWrapper);
        if(result!=null){
            return new JsonResult(0,"此菜品已存在!");
        }

        boolean flag2 = dishService.save(dish);

        DishFlavor dishFlavor = dishDto.gainDishFlavor();     //转换成dishFlavor
        dishFlavor.setDishId(dish.getId());                   //添加上刚生成的菜品ID
        boolean flag1 = dishFlavorSerivce.save(dishFlavor);

        if(!flag1||!flag2){
            return new JsonResult(0,"新增失败,请重试!");
        }
        stringRedisTemplate.opsForList().rightPush(RedisContent.DISH_KEY+dish.getCategoryId(), JSONUtil.toJsonStr(dish));

        return new JsonResult(1,"新增成功");
    }
    //菜品信息分页查询
    @GetMapping("/page")
    public JsonResult page(Integer currentPage,Integer pageSize,String name){
        if(currentPage==null||pageSize==null){
            return new JsonResult(0,"当前页或者当前最大页条目数错误");
        }

        IPage<DishCategoryDto> dtoIPage=new Page<>(currentPage,pageSize);

        name="%"+name+"%";
        IPage<DishCategoryDto> page = dishService.getPage(dtoIPage, name);

        return new JsonResult(1,"",page);
    }
    //根据id查询菜品信息和对应的口味信息
    @GetMapping("/gainByID/{id}")
    public JsonResult get(@PathVariable Long id){
        Dish dish = dishService.getById(id);

        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        DishFlavor result = dishFlavorSerivce.getOne(queryWrapper);
        //合并菜品和菜品口味
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        String sb = result.getValue().substring(1, result.getValue().length() - 1);
        List<String> list = Stream.of(sb.split(",")).collect(Collectors.toList());
        dishDto.setFlavors(list);
        return new JsonResult(1,"",dishDto);
    }
    //修改菜品
    @PostMapping("/update")
    public JsonResult update(@RequestBody DishDto dishDto){
        log.info("图片:"+dishDto.getImage());

        Dish dish = dishDto.gainDish();
        boolean flag2 = dishService.updateById(dish);
        stringRedisTemplate.opsForList().remove(RedisContent.DISH_KEY+dish.getCategoryId(),0,-1);


        DishFlavor dishFlavor = dishDto.gainDishFlavor();     //转换成dishFlavor
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        boolean flag1 = dishFlavorSerivce.update(dishFlavor,queryWrapper);

        if(!flag1||!flag2){
            return new JsonResult(0,"修改失败,请重试!");
        }

        return new JsonResult(1,"修改成功");
    }
    //删除菜品
    @DeleteMapping("/deleteById/{id}")
    public JsonResult deleteById(@PathVariable Long id){
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        boolean flag1 = dishFlavorSerivce.remove(queryWrapper);
        boolean flag2 = dishService.removeById(id);
        stringRedisTemplate.opsForList().remove(RedisContent.DISH_KEY,0,-1);
        if(!flag1||!flag2){
            return new JsonResult(0,"删除失败,请重试!");
        }
        return new JsonResult(1,"删除成功");
    }
    //批量删除
    @PostMapping("/deleteByIds")
    public JsonResult deleteByIds(@RequestBody String[] idsList){

        List<Long> list=new ArrayList<>();
        for(String sid:idsList){
            list.add(Long.valueOf(sid));
        }
        boolean flag1 = dishFlavorSerivce.removeByDishId(list);
        if(!flag1){
            return new JsonResult(0,"删除关联口味失败,请重试!");
        }
        boolean flag2 = dishService.removeByIds(list);
        if(!flag2){
            return new JsonResult(0,"删除菜品失败,请重试!");
        }
        stringRedisTemplate.opsForList().remove(RedisContent.DISH_KEY,0,-1);
        return new JsonResult(1,"删除成功");
    }
    //启售菜品或停售菜品
    @PostMapping("/setStatus")
    public JsonResult setStatus(@RequestBody Dish dish){
        if(dish.getStatus()==1){
            dish.setStatus(0);
        }else{
            dish.setStatus(1);
        }
        boolean flag = dishService.updateById(dish);
        if(!flag){
            return new JsonResult(0,"修改失败,请重试!");
        }
        stringRedisTemplate.opsForList().remove(RedisContent.DISH_KEY,0,-1);
        return new JsonResult(1,"操作成功");
    }
    //批量启售菜品或停售菜品
    @PostMapping("/statusList/{status}")
    public JsonResult statusList(@RequestBody String[] idsList,@PathVariable Integer status){
        for(String sid:idsList){
            Dish dish=new Dish();
            dish.setId(Long.valueOf(sid));dish.setStatus(status);
            boolean flag = dishService.updateById(dish);
            if(!flag){
                return new JsonResult(0,"修改失败,请重试!");
            }
        }
        return new JsonResult(1,"操作成功");
    }
    //获取菜品列表
    @GetMapping("/gainDishList")
    public JsonResult gainDishList(){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        List<Dish> list = dishService.list(queryWrapper);

        List<DishCopiesDto> results=new ArrayList<>();
        DishCopiesDto dishCopiesDto=null;
        for(Dish dish:list){
            dishCopiesDto=new DishCopiesDto();
            dishCopiesDto.gain(dish);
            results.add(dishCopiesDto);
        }
        return new JsonResult(1,"",results);
    }
}
